package com.example.prompt.service.file;


import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@Service
@Slf4j
@RequiredArgsConstructor
public class FileService {

    @Value("${file.upload.dir}")
    private String UPLOAD_DIR;

    /**
     * 文件上传
     * 返回文件名。文件名是UUID
     */
    public String uploadFile(MultipartFile file) {
        try {
            // 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(UPLOAD_DIR);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }
            // 生成UUID作为文件名
            String fileName = UUID.randomUUID().toString();
            // 获取文件扩展名
            String originalFileName = file.getOriginalFilename();
            String fileExtension = originalFileName.substring(originalFileName.lastIndexOf("."));
            // 保存文件
            byte[] bytes = file.getBytes();
            Path path = uploadPath.resolve(fileName + fileExtension);
            Files.write(path, bytes);
            log.info("文件 {} 上传成功，保存为 {}", originalFileName, fileName + fileExtension);
            return fileName+fileExtension;
        } catch (IOException e) {
            log.error("文件上传失败: {}", e.getMessage());
            return "";
        }
    }
}
